﻿using HamcoWcs.Entitys.BaseConfigs;
using HamcoWcs.Entitys.BcrReadInfos;
using HamcoWcs.Entitys.DeviceErrors;
using HamcoWcs.Entitys.Logs;
using HamcoWcs.Entitys.Logss;
using HamcoWcs.Entitys.MainTasks;
using HamcoWcs.Entitys.SubTasks;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Models.DeviceMsgs.SrmMsgs;
using HamcoWcs.Models.Devices;
using HamcoWcs.Models.Events;
using HamcoWcs.Models.ForeEndModels.UITasks;
using HamcoWcs.Models.NodeInfos;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;

namespace HamcoWcs.Workers.SrmWorkers
{
    public partial class PpkSrmWorker
    {
        //private static List
        private void ReadTeachInfoBuffer(NodeInfoDto node)
        {
            foreach (var srm in node.Srms)
            {
                //var content = new SrmTeachMsg(false)
                //{
                //    Row = 1,
                //    Bay = 1,
                //    Lev = 1,
                //    Request = 2
                //}.Encode();
                //node.SrmPlc.Client.Write("D3080", content);
                //node.SrmPlc.Client.Write("D4080", content);

                SrmTeachMsg msg;
                if (srm.PortName == "C1")
                {
                    var c1res = node.SrmPlc.Client.Read("D3080", 14);
                    if (!c1res.IsSuccess) continue;
                    msg = new SrmTeachMsg(c1res.Content, false);
                }
                else
                {
                    var c2res = node.SrmPlc.Client.Read("D4080", 14);
                    if (!c2res.IsSuccess) continue;
                    msg = new SrmTeachMsg(c2res.Content, false);
                }

                srm.TeachMsg = msg;

                if (msg.Request == 2)
                {
                    var locName = $"{msg.Row:00}{msg.Bay:000}{msg.Lev:00}";
                    if (locName.IsShelf())
                    {
                        var loc = _wcsDbContext.WcsLocations.FirstOrDefault(x => x.WcsLocName == locName);
                        if (loc != null)
                        {
                            ShelfTeachInfo shelfTeachInfo;
                            var teachInfoStr = loc.TeachInfo;
                            if (string.IsNullOrEmpty(teachInfoStr))
                            {

                                shelfTeachInfo = new ShelfTeachInfo();
                                if (srm.PortName == "C1")
                                {
                                    shelfTeachInfo.C1 = new SrmTeachInfo(msg);
                                    shelfTeachInfo.C2 = new SrmTeachInfo();
                                    msg.Request = 0;
                                    node.SrmPlc.Client.Write("D3080", msg.Encode());
                                }
                                else
                                {
                                    shelfTeachInfo.C1 = new SrmTeachInfo();
                                    shelfTeachInfo.C2 = new SrmTeachInfo(msg);
                                    msg.Request = 0;
                                    node.SrmPlc.Client.Write("D4080", msg.Encode());
                                }
                                GlobalValue.SrmTeachQueue[$"{srm.DeviceName}"] = "";

                            }
                            else
                            {
                                shelfTeachInfo = JsonConvert.DeserializeObject<ShelfTeachInfo>(teachInfoStr);
                                if (srm.PortName == "C1")
                                {
                                    shelfTeachInfo.C1 = new SrmTeachInfo(msg);
                                    msg.Request = 0;
                                    node.SrmPlc.Client.Write("D3080", msg.Encode());
                                }
                                else
                                {
                                    shelfTeachInfo.C2 = new SrmTeachInfo(msg);
                                    msg.Request = 0;
                                    node.SrmPlc.Client.Write("D4080", msg.Encode());
                                }
                                GlobalValue.SrmTeachQueue[$"{srm.DeviceName}"] = "";

                            }

                            loc.TeachInfo = JsonConvert.SerializeObject(shelfTeachInfo);
                            _wcsDbContext.SaveChanges();
                        }

                    }

                }
                else if (msg.Request == 3)
                {
                    msg.Request = 0;
                    node.SrmPlc.Client.Write("D4080", msg.Encode());
                }

            }
        }

        private void GetTeachInfo(NodeInfoDto node)
        {
            ReadTeachInfoBuffer(node);

            if (!GlobalValue.TeachShelfNames.Any()) return;

            if (GlobalValue.SrmTeachQueue[$"{node.NodeName}-C1"] == "" && GlobalValue.SrmTeachQueue[$"{node.NodeName}-C2"] == "")
            {
                var shelfName = GlobalValue.TeachShelfNames.Dequeue();
                if (!shelfName.IsShelf()) return;

                int row = int.Parse(shelfName[..2]);
                if (row < 1 || row > 4) return;
                if ((row == 1 || row == 2) && node.NodeName == "CJSTW200") return;
                if ((row == 3 || row == 4) && node.NodeName == "CJSTW100") return;

                int bay = int.Parse(shelfName[2..3]);
                int lev = int.Parse(shelfName[5..]);

                var msg = new SrmTeachMsg(false)
                {
                    Row = (ushort)row,
                    Bay = (ushort)bay,
                    Lev = (ushort)lev,
                    Station = 0,
                    Deep = 0,
                    WalkPosition = 0,
                    LiftHighPosition = 0,
                    LiftLowPosition = 0,
                    ForkPosition = 0,
                    Request = 1
                };
                var sendMsg = msg.Encode();
                node.SrmPlc.Client.Write("D3080", sendMsg);
                node.SrmPlc.Client.Write("D4080", sendMsg);
            }
        }
        private DateTime testTime = DateTime.Now;
        private void DoTest(NodeInfoDto node)
        {
            testTime = DateTime.Now;
            node.Srms.ToList().ForEach(x =>
            {
                x.DeviceMode = 1;
                x.IsTask = 0;
            });
            //node.UpdateSrmState();
            //DealGlobalConfig(node);
            if (node.UpdateSrmStateByAll())
            {
                string f = "";
                if (node.MachineState == EnumMachineState.IDLE)
                {
                    f = "LOW";
                }
                else
                {
                    f = "HIGH";
                }
                if (!f.IsNullOrEmpty())
                {
                    _mesCommunicateService.MachineFrequencyRequest(node.NodeName, f);
                    var cfg = node.NodeName == "CJSTW100" ? "CJSTW100STATE" : "CJSTW200STATE";
                    _config.SetConfigMsg(cfg, f);

                    var de = new DeviceEvent()
                    {
                        MachineName = node.NodeName,
                        PortName = "",
                        Description = f,
                        SetTime = DateTime.Now,
                    };
                    _wcsDbContext.Set<DeviceEvent>().Add(de);
                    _wcsDbContext.SaveChanges(); ;
                }
            }
            node.UpdateWholeSrmState();
        }
        private bool DealRecv(NodeInfoDto node)
        {
            var srmPlc = node.SrmPlc;
            if (!srmPlc.ConnectionStatus)
                srmPlc.ConnectToPlc();
            if (!srmPlc.ConnectionStatus)
            {
                var oldCS = node.MachineControlState;

                node.MachineControlState = EnumMachineControlState.OFFLINE;
                if (oldCS != node.MachineControlState)
                {
                    _mesCommunicateService.MachineControlStateChanged(node);
                    var k = $"{node.NodeName}CONTROLSTATE";
                    _config.SetConfigMsg(k, ((int)node.MachineControlState).ToString());

                }
                return false;
            }

            try
            {
                GetTeachInfo(node);
            }
            catch (Exception ex)
            {
                _logger.AddSystemErrorLog($"PpkSrmWorker->DealRecv->GetTeachInfo:{ex.Message}");
            }

            try
            {
                DealRecv(srmPlc);

                node.UpdateSrmState();
                if (node.UpdateSrmStateByAll())
                {
                    string f = "";
                    if (node.MachineState == EnumMachineState.IDLE)
                    {
                        f = "LOW";
                    }
                    else if (node.MachineState == EnumMachineState.RUN)
                    {
                        f = "HIGH";
                    }
                    if (!f.IsNullOrEmpty())
                    {
                        _mesCommunicateService.MachineFrequencyRequest(node.NodeName, f);
                        var cfg = node.NodeName == "CJSTW100" ? "CJSTW100STATE" : "CJSTW200STATE";
                        _config.SetConfigMsg(cfg, f);

                        var de = new DeviceEvent()
                        {
                            MachineName = node.NodeName,
                            PortName = "",
                            Description = f,
                            SetTime = DateTime.Now,
                        };
                        _wcsDbContext.Set<DeviceEvent>().Add(de);
                        _wcsDbContext.SaveChanges(); ;
                    }
                }
                node.UpdateWholeSrmState();
                var oldCS = node.MachineControlState;
                if (node.Srms.All(x => x.DeviceMode == 2) && node.Srms.All(x => x.ErrorCode == 0))
                {
                    node.MachineControlState = EnumMachineControlState.ONLINELOCAL;
                }
                else
                {
                    node.MachineControlState = EnumMachineControlState.ONLINEREMOTE;
                }

                if (oldCS != node.MachineControlState)
                {
                    _mesCommunicateService.MachineControlStateChanged(node);
                    var k = $"{node.NodeName}CONTROLSTATE";
                    _config.SetConfigMsg(k, ((int)node.MachineControlState).ToString());
                }
            }
            catch (Exception ex)
            {
                _logger.AddSystemErrorLog($"PpkSrmWorker->DealRecv:{ex.Message}");
                srmPlc.DisconnectToPlc();
                return false;
            }
            return true;

            //}
        }


        private void OnMachineStateChanged(object sender, StateChangeEvent e)
        {
            _machineStateService.SaveMachineState(e.MachineName, e.MachineState);
            _mesCommunicateService.MachineStateChanged(e.MachineName, e.MachineState);
        }

        private void DealRecv(SrmPlc srmPlc)
        {
            if (!srmPlc.ConnectionStatus) return;

            GetReadRate(srmPlc);
            GetGlobalPara(srmPlc);
            GetMileage(srmPlc);
            CabinetErrorHandler(srmPlc);

            foreach (var srm in srmPlc.Srms.Values)
            {
                SrmNoTaskHandler(srm);

                var dbInfo = srmPlc.DbInfo.FirstOrDefault(x => x.DbName == $"{srm.PortName}_recv".ToLower());
                if (dbInfo == null) continue;

                srmPlc.Client.ReceiveTimeOut = 10;
                var recv = srmPlc.Client.Read("D" + dbInfo.StartPoint, (ushort)(dbInfo.DbLength / 2));

                if (!recv.IsSuccess)
                    throw new Exception("读取异常，断开重连");

                var msgDto = new SrmRecvMsg(recv.Content, false);
                HandelSrmBlock(srm, msgDto);
                ErrorHandel(srm, msgDto);
                srm.Update(msgDto);

                // recv 消息号等于回复时没有请求
                if (msgDto.Number == msgDto.Response) continue;
                var res = BitConverter.GetBytes(msgDto.Number);

                if (msgDto.Request == 0)
                {
                    _logger.AddCommunicationLog(new CommunicationLog("WCS << SRM")
                    {
                        TransactionId = $"{DateTime.Now:yyyyMMddHHmmssffffff}",
                        Receiver = "WCS",
                        Sender = srm.DeviceName,
                        Content = msgDto.ToJson(),
                        MessageName = ((EnumSrmRecvMsg)msgDto.Request).ToString(),
                        MessageStatus = $"number:{msgDto.Number}",
                        MessageType = "",
                        Return = "",
                        UnitId = msgDto.UnitId,
                    });

                    srmPlc.Client.Write("D" + (dbInfo.StartPoint + 28), res);
                    continue;
                }
                //如果Plc有消息request，进行消息处理

                try
                {
                    var parser = _srmParseFactory.CreateParser(srm);
                    parser.Deal(srm, srmPlc);
                }
                catch (Exception ex)
                {
                    _logger.AddSystemErrorLog($"PpkSrmWorker->DealRecv:{ex.Message}");
                }

                _logger.AddCommunicationLog(new CommunicationLog("WCS << SRM")
                {
                    TransactionId = $"{DateTime.Now:yyyyMMddHHmmssffffff}",
                    Receiver = "WCS",
                    Sender = srm.DeviceName,
                    Content = msgDto.ToJson(),
                    MessageName = ((EnumSrmRecvMsg)msgDto.Request).ToString(),
                    MessageStatus = $"number:{msgDto.Number}",
                    MessageType = "",
                    Return = "",
                    UnitId = msgDto.UnitId,
                });

                //处理完成将回复改为跟消息号一致
                srmPlc.Client.Write("D" + (dbInfo.StartPoint + 28), res);
            }
        }

        private void CabinetErrorHandler(SrmPlc srmPlc)
        {
            /*
                地址D5001
                报警代码：1000 地面柜烟感报警
                报警代码：1001 地面柜温度异常
            */
            var res = srmPlc.Client.Read("D5001", 1);
            if (res.IsSuccess)
            {
                var d5001 = res.Content;
                var t = BitConverter.ToUInt16(d5001);

                var errorDetail = "";
                if (t == 1000) errorDetail = "地面柜烟感报警";
                if (t == 1001) errorDetail = "地面柜温度异常";

                var error = new DeviceErrorQueue()
                {
                    CreatedTime = DateTime.Now,
                    ErrorCode = t.ToString(),
                    ErrorDetail = errorDetail,
                    ErrorLevel = "1",
                    LastUpdateTime = DateTime.Now,
                    MachineName = srmPlc.PlcName,
                    PortName = "-",
                    PlcName = srmPlc.PlcName
                };
                if (t == 1000 || t == 1001)
                {

                }
                else
                {
                    var d = _wcsDbContext.DeviceErrorQueues.FirstOrDefault(x => x.MachineName == srmPlc.PlcName && x.PortName == "-");
                    if (d == null) return;
                    d.LastUpdateTime = DateTime.Now;

                    // 过滤一秒以内的报错
                    var duration = (d.LastUpdateTime - d.CreatedTime);
                    if (d != null)
                    {
                        var l = new DeviceErrorLog()
                        {
                            SetTime = duration.GetDuration(),
                            CreatedTime = d.CreatedTime,
                            LastUpdateTime = d.LastUpdateTime,
                            DeviceName = srmPlc.PlcName,
                            ErrorCode = d.ErrorCode,
                            ErrorDetail = d.ErrorDetail,
                            PlcName = srmPlc.PlcName,
                        };
                    }
                    _wcsDbContext.Remove(d);
                    _wcsDbContext.SaveChanges();
                }
            }
        }

        /// <summary>堆垛机无任务有货情况自动入库</summary>
        private void SrmNoTaskHandler(SrmDto srm)
        {
            var srmTask = _wcsDbContext.SubTasks
                .Where(x => x.PlcName == srm.SrmName)
                .Where(x => x.TaskStatus == nameof(EnumSubTaskStatus.OnProgress));

            bool isExistsSrrmTask = _wcsDbContext.SubTasks
                .Where(x => x.PlcName == srm.SrmName)
                .Where(x => x.TaskStatus == nameof(EnumSubTaskStatus.OnProgress))
                .Any();

            var sss = _config.TryGetConfigValue("SrmNoTaskIsGoodsTime", out string srmNoTaskIsGoodsTimeThresholdStr);
            //var sss = _wcsDbContext.BaseConfigs.FirstOrDefault(x => x.ConfigKey == "SrmNoTaskIsGoodsTime");
            int srmNoTaskIsGoodsTimeThreshold = GlobalValue.DefaultSrmNoTaskIsGoodsTimeThreshold;
            if (sss)
            {
                srmNoTaskIsGoodsTimeThreshold = (int.Parse(srmNoTaskIsGoodsTimeThresholdStr)) * 60;
            }

            if (srm.IsGoods == 1 && srm.IsTask == 0 && !isExistsSrrmTask)
            {
                srm.NoTaskTick++;
            }
            else
            {
                srm.NoTaskTick = 0;
            }


            if (srm.NoTaskTick == srmNoTaskIsGoodsTimeThreshold)
            {
                var result = SrmIsGoodsNoTask(srm);
                if (!result)
                {
                    srm.NoTaskTick--;
                }
            }
        }

        /// <summary>
        /// 读取里程
        /// </summary>
        /// <param name="srmPlc"></param>
        private void GetMileage(SrmPlc srmPlc)
        {
            try
            {
                var dbInfo1 = srmPlc.DbInfo.FirstOrDefault(x => x.DbName == $"c1_mile");

                var recv1 = srmPlc.Client.Read("D" + dbInfo1.StartPoint, (ushort)(dbInfo1.DbLength / 2));
                if (!recv1.IsSuccess)
                {
                    throw new Exception("读取C1里程异常");
                }
                dbInfo1.Buffer = recv1.Content;

                var dbInfo2 = srmPlc.DbInfo.FirstOrDefault(x => x.DbName == $"c2_mile");

                var recv2 = srmPlc.Client.Read("D" + dbInfo2.StartPoint, (ushort)(dbInfo2.DbLength / 2));
                if (!recv2.IsSuccess)
                {
                    throw new Exception("读取C2里程异常");
                }
                dbInfo2.Buffer = recv2.Content;

            }
            catch (Exception ex)
            {
                _logger.AddSystemErrorLog($"ReadDb->{srmPlc.PlcName}:{ex.Message}");
            }
        }

        private static void GetGlobalPara(SrmPlc srmPlc)
        {
            try
            {
                var c1List = new List<string>();
                var c2List = new List<string>();
                var readErrorFlag = false;

                foreach (var addr in GlobalValue.SrmAddrs)
                {
                    var c1Addr = $"D{addr}";
                    var c2Addr = $"D{addr + 400}";

                    var a = srmPlc.Client.Read(c1Addr, 1);
                    var b = srmPlc.Client.Read(c2Addr, 1);

                    if (a.IsSuccess && b.IsSuccess)
                    {
                        c1List.Add((BitConverter.ToUInt16(a.Content) * 0.1).ToString("F1"));
                        c2List.Add((BitConverter.ToUInt16(b.Content) * 0.1).ToString("F1"));
                        //c2List.Add(BitConverter.ToUInt16(b.Content) * 0.1);
                    }
                    else
                    {
                        readErrorFlag = true;
                        break;
                    }
                }

                if (!readErrorFlag)
                {
                    var srmc1 = srmPlc.Srms.Values.FirstOrDefault(x => x.PortName == "C1");
                    var srmc2 = srmc1.AnotherSrm;

                    srmc1.GlobalPara = string.Join('|', c1List);
                    srmc2.GlobalPara = string.Join('|', c2List);
                }
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        ///  读取读码率
        /// </summary>
        /// <param name="srmPlc"></param>
        private static void GetReadRate(SrmPlc srmPlc)
        {
            if (ReadRateWorker.SrmBcrReadFlag)
            {
                try
                {
                    var a = srmPlc.Client.Read("D5195", 4);
                    var c1_op_s = BitConverter.ToUInt16(a.Content, 0);
                    var c1_op_f = BitConverter.ToUInt16(a.Content, 2);
                    var c1_hp_s = BitConverter.ToUInt16(a.Content, 4);
                    var c1_hp_f = BitConverter.ToUInt16(a.Content, 6);

                    var b = srmPlc.Client.Read("D5595", 4);
                    var c2_op_s = BitConverter.ToUInt16(a.Content, 0);
                    var c2_op_f = BitConverter.ToUInt16(a.Content, 2);
                    var c2_hp_s = BitConverter.ToUInt16(a.Content, 4);
                    var c2_hp_f = BitConverter.ToUInt16(a.Content, 6);

                    var aisle = srmPlc.Srms.Values.First().MachineName == "CJSTW100" ? "短" : "长";
                    var now = DateTime.Now;

                    var setTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0);
                    setTime = setTime.AddHours(-1);


                    var readRates = new List<BcrReadInfo>()
                    {
                        new BcrReadInfo($"BCR_{aisle}_C1_OP",c1_op_s,c1_op_f,setTime),
                        new BcrReadInfo($"BCR_{aisle}_C1_HP",c1_hp_s,c1_hp_f,setTime),
                        new BcrReadInfo($"BCR_{aisle}_C2_OP",c2_op_s,c2_op_f,setTime),
                        new BcrReadInfo($"BCR_{aisle}_C2_HP",c2_hp_s,c2_hp_f,setTime),
                    };

                    lock (ReadRateWorker.Lock)
                    {
                        ReadRateWorker.ReadInfos.AddRange(readRates);
                    }

                    var t1 = srmPlc.Client.Read("D5384", 1);
                    if (t1.IsSuccess)
                    {
                        var v = BitConverter.ToUInt16(t1.Content, 0);
                        if (v >= 9999) v = 1;
                        else v++;

                        srmPlc.Client.Write("D5384", BitConverter.GetBytes(v));
                    }

                    var t2 = srmPlc.Client.Read("D5784", 1);
                    if (t2.IsSuccess)
                    {
                        var v = BitConverter.ToUInt16(t2.Content, 0);
                        if (v >= 9999) v = 1;
                        else v++;

                        srmPlc.Client.Write("D5784", BitConverter.GetBytes(v));
                    }

                }
                catch (Exception)
                {

                }

                ReadRateWorker.SrmBcrReadFlag = false;
            }
        }

        private void ErrorHandel(SrmDto srm, SrmRecvMsg msg)
        {
            // 触发异常
            if (msg.DeviceMode == 4 && srm.DeviceMode != 4)
            {
                var a = _wcsDbContext.DeviceErrorQueues.Any(x => x.MachineName == srm.MachineName && x.PortName == srm.PortName);
                if (a) return;

                var errorCode = msg.ErrorCode.ToString();
                var alarm = GetAlarm(errorCode);
                var errorDetail = alarm.AlarmName;
                if (string.IsNullOrEmpty(alarm.AlarmName)) return;
                var arg = GetAlarmArgs(srm.MachineName, errorCode);
                if (!string.IsNullOrEmpty(arg))
                {
                    errorDetail = string.Format(alarm.AlarmName, arg);
                }
                var d = new DeviceErrorQueue()
                {
                    CreatedTime = DateTime.Now,
                    ErrorCode = errorCode,
                    ErrorDetail = errorDetail,
                    ErrorLevel = alarm.Level.ToString(),
                    LastUpdateTime = DateTime.Now,
                    MachineName = srm.MachineName,
                    PortName = srm.PortName,
                    PlcName = srm.PlcName
                };


                _wcsDbContext.DeviceErrorQueues.Add(d);
                _wcsDbContext.SaveChanges();
                _mesCommunicateService.AlarmReportSet(d);
            }
            // 解除异常
            else if (msg.DeviceMode != 4 && srm.DeviceMode == 4 || msg.DeviceMode != 4 && srm.DeviceMode != 4)
            {
                srm.AlarmTick = 0;
                var d = _wcsDbContext.DeviceErrorQueues.FirstOrDefault(x => x.MachineName == srm.MachineName && x.PortName == srm.PortName);

                if (d is null) return;


                d.LastUpdateTime = DateTime.Now;

                // 过滤一秒以内的报错
                var duration = (d.LastUpdateTime - d.CreatedTime);
                if (duration.TotalSeconds > 5)
                {
                    var l = new DeviceErrorLog()
                    {
                        SetTime = duration.GetDuration(),
                        CreatedTime = d.CreatedTime,
                        LastUpdateTime = d.LastUpdateTime,
                        DeviceName = srm.DeviceName,
                        ErrorCode = d.ErrorCode,
                        ErrorDetail = d.ErrorDetail,
                        PlcName = srm.PlcName,
                    };
                    _wcsDbContext.DeviceErrorLogs.Add(l);
                }

                _wcsDbContext.Remove(d);
                _wcsDbContext.SaveChanges();
                _mesCommunicateService.AlarmReportClear(d);
            }
            else
            {
                srm.AlarmTick = 0;
            }
        }

        private AlarmExplanation GetAlarm(string errorCode)
        => _wcsDbContext.AlarmExplanations
                   .Where(x => x.Module == "srm")
                   .Where(x => x.Code == errorCode)
                   .FirstOrDefault()
        ?? AlarmExplanation.GetUnkAlarm(errorCode);

        private string GetAlarmArgs(string machineName, string errorCode)
        {
            var isCJSTW100 = machineName == "CJSTW100";
            var arg = "";
            switch (errorCode)
            {
                case "473":
                case "490":
                    arg = isCJSTW100 ? "C1-CJVCV200：36" : "C2-CJVCV400：42";
                    break;
                case "474":
                case "491":
                    arg = isCJSTW100 ? "C1-CJVCV800：35" : "C2-CJVCV300：40";
                    break;
                case "475":
                case "492":
                    arg = isCJSTW100 ? "C1-CJVCV700：28" : "C2-CJVCV200：36";
                    break;
                case "476":
                case "493":
                    arg = isCJSTW100 ? "C1-CJRCV400：8" : "C2-CJVCV100：9";
                    break;
                case "477":
                case "494":
                    arg = isCJSTW100 ? "C1-CJRCV300：6" : "C2-CJRCV200：4";
                    break;
                case "478":
                case "495":
                    arg = isCJSTW100 ? "C1-CJVCV100：9" : "C2-CJRCV100：2";
                    break;
            };

            return arg;
        }
        /// <summary>
        /// 堆垛机有货无任务自动入库
        /// </summary>
        /// <param name="srm"></param>
        /// <returns></returns>
        /// <exception cref="WarningException"></exception>
        private bool SrmIsGoodsNoTask(SrmDto srm)
        {
            {
                var Loc = _locationService.GetEmptyLocationBySrm(srm.SrmName);
                if (Loc == null) { return false; }


                var fLoc = srm.Aisle.NodeName == "CJSTW100" ? "CJRCV300" : "CJRCV100";



                var create = new MainTaskCreate()
                {
                    TaskType = EnumMainTaskType.InboundTask.ToString(),
                    FromLoc = fLoc,
                    ToLoc = Loc.WcsLocName,
                    UnitId = $"UNKNOWN-{DateTime.Now:HHmmssfff}"
                };


                var fAddr = _baseMainTaskService.GetTargetAddress(create.FromLoc);
                var tAddr = _baseMainTaskService.GetTargetAddress(create.ToLoc, false);

                var path = _pathService.GetPath(fAddr.MachineName, tAddr.MachineName)
                    ?? throw new WarningException("未找到该路径");

                var task = new MainTask()
                {
                    SrcMachine = fAddr.MachineName,
                    SrcPosition = fAddr.PositionName,
                    SrcType = fAddr.PositionType,
                    SrcZone = fAddr.ZoneName,
                    DesMachine = tAddr.MachineName,
                    DesPosition = tAddr.PositionName,
                    DesType = tAddr.PositionType,
                    DesZone = tAddr.ZoneName,
                    Sender = "WCS",
                    TaskId = $"{create.UnitId}-WCS",
                    UnitId = create.UnitId,
                    Priority = GlobalValue.DEFAULT_TASK_PRIORITY,
                    TaskStatus = EnumMainTaskStatus.OnProgress.ToString(),
                    MainTaskType = nameof(EnumMainTaskType.InboundTask),
                    CreatedTime = DateTime.Now,
                    Path = path.UsedPath,
                    ActiveSubTaskId = 1,
                    TotalSubTaskNum = 1,
                };


                var sub = new SubTask()
                {
                    SubTaskId = "",
                    SubTaskType = EnumSubTaskType.SrmInTask.ToString(),
                    UnitId = task.UnitId,
                    FromLoc = task.SrcMachine,
                    ToLoc = Loc.WcsLocName,
                    TaskStatus = EnumSubTaskStatus.OnProgress.ToString(),
                    TaskFrom = "WCS",
                    PlcName = srm.SrmName,
                    MainTask = task,
                    TaskSeq = 1
                };
                _wcsDbContext.SubTasks.Add(sub);

                _wcsDbContext.Set<MainTask>().Add(task);
                _wcsDbContext.SaveChanges();



                //_baseMainTaskService.CreateTaskByWcs(create);
                //var task = _wcsDbContext.MainTasks.FirstOrDefault(x => x.UnitId == create.UnitId);
                //if (task != null)
                //{
                //    var sub = new SubTask()
                //    {
                //        SubTaskId = "1",
                //        SubTaskType = EnumSubTaskType.SrmInTask.ToString(),
                //        UnitId = "unknown",
                //        FromLoc = task.SrcMachine,
                //        ToLoc = Loc.WcsLocName,
                //        TaskStatus = EnumSubTaskStatus.OnProgress.ToString(),
                //        TaskFrom = "WCS",
                //        MainTask = task,
                //        PlcName = task.DesMachine
                //    };
                //    _wcsDbContext.SubTasks.Add(sub);
                //    task.TaskStatus = EnumMainTaskStatus.OnProgress.ToString();
                //_wcsDbContext.SaveChanges();
                return true;
            }

        }
    }

}

